package com.ruoyi.app.controller.student;

import cn.hutool.core.collection.CollectionUtil;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ruoyi.app.controller.student.vo.AppStudentCreateReqVo;
import com.ruoyi.app.controller.student.vo.AppStudentRespVo;
import com.ruoyi.app.controller.student.vo.AppStudentUpdateReqVo;
import com.ruoyi.app.domain.AppActivity;
import com.ruoyi.app.domain.AppActivityReg;
import com.ruoyi.app.domain.AppCreditRules;
import com.ruoyi.app.domain.AppStudent;
import com.ruoyi.app.mapper.AppActivityRegMapper;
import com.ruoyi.app.service.IAppStudentService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;

import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;

/**
 * 学生Controller
 *
 * @author ruoyi
 * @date 2025-01-11
 */
@RestController
@RequestMapping("/app/student")
public class AppStudentController extends BaseController {
    @Autowired
    private IAppStudentService schStudentService;

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private AppActivityRegMapper appActivityRegMapper;
    @GetMapping("/listForSelect")
    public AjaxResult listForSelect() {
        AppStudent schStudent = new AppStudent();
        List<AppStudentRespVo> list = schStudentService.selectAppStudentList(schStudent);
        return AjaxResult.success(list);
    }
    /**
     * 查询学生列表
     */
    @GetMapping("/list")
    public TableDataInfo list(AppStudent schStudent) {
        startPage();
        List<AppStudentRespVo> list = schStudentService.selectAppStudentList(schStudent);
        if (CollectionUtil.isNotEmpty(list)) {
            for (AppStudentRespVo appStudentRespVo : list) {
                MPJLambdaWrapper<AppActivityReg> lwq = new MPJLambdaWrapper<AppActivityReg>()
                        .selectAll(AppActivityReg.class)
                        .select(AppCreditRules::getPoints)
                        .leftJoin(AppActivity.class,AppActivity::getActivityId,AppActivityReg::getActivityId)
                        .leftJoin(AppCreditRules.class,AppCreditRules::getRuleId,AppActivity::getRuleId)
                        .eq(AppActivityReg::getUserId, appStudentRespVo.getUserId())
                        .eq(AppActivityReg::getStatus,"1");
                List<AppActivityReg> dtos = appActivityRegMapper.selectJoinList(AppActivityReg.class,lwq);
                appStudentRespVo.setPoints(dtos.stream().map(x->x.getPoints()).reduce(BigDecimal::add).orElse(BigDecimal.ZERO));
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出学生列表
     */
    @Log(title = "学生", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AppStudent schStudent) {
        List<AppStudentRespVo> list = schStudentService.selectAppStudentList(schStudent);
        ExcelUtil<AppStudentRespVo> util = new ExcelUtil<AppStudentRespVo>(AppStudentRespVo.class);
        util.exportExcel(response, list, "学生数据");
    }

    /**
     * 获取学生详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(schStudentService.selectAppStudentById(id));
    }

    /**
     * 新增学生
     */
    @Log(title = "学生", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AppStudentCreateReqVo req) {

        SysUser user = new SysUser();
        user.setUserName(req.getUserName());
        user.setPhonenumber(req.getPhonenumber());
        user.setEmail(req.getEmail());

        if (!userService.checkUserNameUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        return toAjax(schStudentService.insertAppStudent(req));
    }

    /**
     * 修改学生
     */
    @Log(title = "学生", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AppStudentUpdateReqVo schStudent) {
        SysUser user = new SysUser();
        user.setUserName(schStudent.getUserName());
        user.setPhonenumber(schStudent.getPhonenumber());
        user.setEmail(schStudent.getEmail());
        user.setUserId(schStudent.getUserId());
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        return toAjax(schStudentService.updateAppStudent(schStudent));
    }

    /**
     * 删除学生
     */
    @Log(title = "学生", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(schStudentService.deleteAppStudentByIds(ids));
    }
}
